import { Button, Cascader, Modal } from 'antd';
import FormRender, { useForm } from 'form-render';
import { connect } from 'umi';
import { useRequest } from 'ahooks';
import {
  getCategoryEffect,
} from '@/services/goods/productManageApproval';
import { useDispatch, useSelector } from '@umijs/max';

const EditForm = (props) => {
  const dispatch = useDispatch();
  const { actionRef } = props;
  const { showForm, loading, queryInfo } = useSelector((state) => state.productManageApproval);

  const form = useForm();

  const onSuccess = ({ code }) => {
    if (code && code === 200) {
      dispatch({
        type: 'productManageApproval/update',
        payload: {
           showForm: false, queryInfo: {}, drawerType: '',
        },
      });
      ref?.current?.reload();
    }
  };

  // 驳回
  const { run: deleteAsync } = useRequest(
    getCategoryEffect,
    {
      manual: true,
      onSuccess: onSuccess
    }
  );
  const update = (data) => {
    dispatch({
      type: 'productManageApproval/updateState',
      payload: data,
    });
  };

  const schema = {
    type: 'object',
    properties: {
      reason: {
        title: '原因',
        type: 'string',
        max: 20,
        widget: 'textArea',
        props: {
          row: 4,
        },
      },
    },
  };

  const onFinish = (data) => {
    deleteAsync({
      id: queryInfo.id,
      auditStatus:2,
      ...data,
    });
  };

  const watch = {
    parr: (val) => {
      if (val) {
        if (val.length === 1 && val[0] === '0') {
          form.setFields([{ name: 'level', value: 1 }]);
        } else if (val.length > 0) {
          form.setFields([{ name: 'level', value: val.length + 1 }]);
        }
      }
    },
    level: (val) => {
      if (val === 3) {
        form.setFields([{ name: 'status', value: 1 }]);
      }
    },
  };

  return (
    <Modal
      title="驳回"
      open={showForm}
      destroyOnClose
      onCancel={() => {
        form.resetFields();
        update({ showForm: false, queryInfo: {}, drawerType: '' });
      }}
      footer={
        <>
          <Button type="primary" loading={loading} onClick={form.submit}>
            确认
          </Button>
          <Button onClick={() =>{
            dispatch({
              type: 'productManageApproval/update',
              payload: {
                 showForm: false, queryInfo: {}, drawerType: '',
              },
            });
          }}>取消</Button>
        </>
      }
    >
      <FormRender
        widgets={{ cascader: Cascader }}
        form={form}
        watch={watch}
        schema={schema}
        onFinish={onFinish}
      />
    </Modal>
  );
};

export default connect(({ productManageApproval, loading }) => {
  return {
    productManageApproval,
    loading: loading.effects['productManageApproval/selectPage'],
  };
})(EditForm);
